package mobi.greenplate.theweb.repository;

import mobi.greenplate.theweb.domain.Transport;
import java.util.List;
import java.util.ArrayList;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import mobi.greenplate.theweb.domain.User;
import mobi.greenplate.theweb.user.UserUtils;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("transportRepository")
public class TransportRepository {

    private EntityManager entityManager;

    @PersistenceContext
    void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @Transactional
    public void delete(Long id) {
        final Transport forDelete = entityManager.getReference(Transport.class, id);
        entityManager.remove(forDelete);
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @Transactional
    public Transport save(Transport transport, User owner) {
        transport.setOwner(owner);
        return entityManager.merge(transport);
    }
    
    @RolesAllowed(value = {"ROLE_USER"})
    public Transport findById(Long id) {
        final Transport transport = entityManager.find(Transport.class, id);
        if(null==transport){
            throw new IllegalArgumentException("transport with id="+id+" not found");
        }
        return transport;        
    }

    public int countAll() {
        return ((Integer) entityManager.createQuery("SELECT count(o) from Transport o").
                getSingleResult()).intValue();
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @Transactional
    public List<Transport> findAll(int firstResult, int maxResult) {
        final List<Transport> founded = entityManager.createQuery("SELECT o FROM Transport o").
                setFirstResult(firstResult).
                setMaxResults(maxResult).getResultList();
        return new ArrayList<Transport>(founded);
    }


    //ManyToOne by owner
    public int countByOwner(Long ownerId) {
        return ((Integer) entityManager.createQuery("SELECT count(o) from Transport o WHERE o.ownerId=:ownerId").
                setParameter("ownerId", ownerId).
                getSingleResult()).intValue();
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @Transactional
    public List<Transport> findByOwner(int firstResult, int maxResult, Long ownerId) {
        final List<Transport> founded = entityManager.createQuery("SELECT o FROM Transport o WHERE o.ownerId=:ownerId").
                setParameter("ownerId", ownerId).
                setFirstResult(firstResult).
                setMaxResults(maxResult).getResultList();
        return new ArrayList<Transport>(founded);
    }    


    
    
}
